package cn.rongdao.jrkabao.ui.IdentificationVerificate;

import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.takephoto.ValidateIDCardInfoByYiTuBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.model.EditUserIdentificationInfoModel;
import cn.rongdao.jrkabao.model.takephoto.IdCardNameAndNumberFromYiTuModel;


/**
 * Created by jiangyongxing on 2016/12/2.
 * 描述：
 */

public abstract class IdentificationActivity extends BaseAutoFinishActivity implements View.OnClickListener {


    public static final int REQUEST_CODE_LIVENESSACTIVITY = 6;
    public static final int RESULT_CODE_INTO_THIS_BY_CASH = 1;
    public static final int RESULT_CODE_INTO_THIS_BY_LOAN = 2;


    protected EditText nameEditText;
    protected EditText numberEditText;
    private String numberStr;
    private String nameStr;
    protected TextView mNumberEdit;
    protected TextView mNameEdit;
    protected String mNameStr;
    protected String mNumberStr;
    private TitleBarUIComponent titleBarUIComponent;
    protected TextView mSubmit;
    private boolean mHasNumber;
    private boolean mHasName;


    @Override
    protected int layoutRes() {
        return R.layout.activity_identification_verificate;
    }


    @Override
    protected void initView() {
        initData();
        nameEditText = (EditText) findViewById(R.id.aiv_name);
        numberEditText = (EditText) findViewById(R.id.aiv_number);
        mNumberEdit = (TextView) findViewById(R.id.aiv_number_edit);
        mNameEdit = (TextView) findViewById(R.id.aiv_name_edit);
        mSubmit = (TextView) findViewById(R.id.aiv_submit);
        initTitleBar();
        initListener();
        initDataFromServerOrFrontActivity();
    }

    private void initDataFromServerOrFrontActivity() {
        if (TextUtils.isEmpty(numberStr) || TextUtils.isEmpty(nameStr)) {
            mNumberEdit.setVisibility(View.GONE);
            mNameEdit.setVisibility(View.GONE);
            IdCardNameAndNumberFromYiTuModel.getInstance().execute(new FRBaseObserver<ValidateIDCardInfoByYiTuBean>(this) {
                @Override
                protected void onBaseNext(ValidateIDCardInfoByYiTuBean data) {
                    if (!TextUtils.isEmpty(data.getName()) || !TextUtils.isEmpty(data.getCitizen_id()))
                        setData(data.getName(), data.getCitizen_id());
                }

                @Override
                protected void onBaseError(Throwable t) {
                    handingExceptions(t, false);
                }
            });
        } else {
            mHasName = true;
            mHasNumber = true;
            setData(nameStr, numberStr);
        }
    }

    protected void initData() {
        try {
            numberStr = getIntent().getStringExtra("number");
            nameStr = getIntent().getStringExtra("name");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initListener() {
        mNumberEdit.setOnClickListener(this);
        mNameEdit.setOnClickListener(this);
        mSubmit.setOnClickListener(this);
        nameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mHasName = s.toString().trim().length() > 0;
                setButtonBackground();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        numberEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当用户输入的字符<15位的时候，不用给button设置颜色，防止重复设置颜色
                if (s.toString().trim().length() < 15)
                    return;
                mHasNumber = s.toString().trim().length() == 18;
                setButtonBackground();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setButtonBackground() {
        mSubmit.setBackgroundResource((mHasName && mHasNumber) ? R.drawable.btn_enable_bg : R.drawable.btn_disable_bg);
    }


    private void setData(String nameStr, String numberStr) {
        nameEditText.setText(nameStr);
        numberEditText.setText(numberStr);
        numberEditText.setSelection(numberEditText.getText().length());
        nameEditText.setSelection(nameEditText.getText().length());
        setButtonBackground();
    }

    private void initTitleBar() {
        titleBarUIComponent = (TitleBarUIComponent) findViewById(R.id.adlg_titlebar);
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        titleBarUIComponent.initTitleBlack(setTitle());
        titleBarUIComponent.initLeftBackBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBarUIComponent.initRightHelpCenterBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startHelpCenter();
            }
        });
    }

    protected abstract String setTitle();

    protected abstract void saveIdCardInfoSuccess();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.aiv_number_edit:
                nameEditText.clearFocus();
                break;
            case R.id.aiv_name_edit:
                nameEditText.setSelection(nameEditText.getText().length());
                break;
            case R.id.aiv_submit:
                //如果用户已经验证过身份信息，就不再保存
                if (validata()) return;
                saveIdCardInfo();
                break;
        }
    }


    private void saveIdCardInfo() {
        EditUserIdentificationInfoModel.getInstance().execute(mNameStr, mNumberStr,new FRBaseObserver<String>(this, "正在保存，请稍候...") {
            @Override
            protected void onBaseNext(String data) {
//                GIOForBuringPointUtil.realNameValidateSuccess();
                FRSharedPreferences.setStringDefault(SPConstant.ID_CARD, mNumberStr);
                FRSharedPreferences.setStringDefault(SPConstant.NAME, mNameStr);
                saveIdCardInfoSuccess();
                FRToast.showToastSafe("身份信息保存成功");
            }
        });
    }



    private boolean validata() {
        mNameStr = nameEditText.getText().toString().trim();
        mNumberStr = numberEditText.getText().toString().trim();
        if (TextUtils.isEmpty(mNameStr)) {
            FRToast.showToastSafe("姓名不能为空");
            return true;
        }
        if (TextUtils.isEmpty(mNameStr)) {
            FRToast.showToastSafe("姓名不能为空");
            return true;
        }
        if (mNameStr.contains("x")) {
            mNameStr = mNameStr.replaceAll("x", "X");
        }
        return false;
    }

}
